var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;

lay('.starttime').each(function () {
    laydate.render({
        elem: this
    });
});

let userList;
let unitList;
let operationNoList = [];
let salesmanCodeList = [];
let inquiryPlatformList=[];
function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if (item["code"] === user.code) {
            tmparr["selected"] = true;
        }
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }

    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}
//操作员、业务员
$.ajax({
    type : 'POST',
    url:'user/getAllUserNameAndCode',
    dataType:"json",
    contentType: 'application/json;charset=utf-8',
    success:function(res){
        if(res.status == 200){
            if(res.data){
                userList = res.data;
            }else{
                layer.msg(res.msg,{icon:0});
            }
        }else{
            layer.msg(res.msg,{icon:4});
        }
    }
});

let currencyList = getdictionary(5,14);//币种
//询盘平台
let inquiryPlatform = getdictionary(6, 61);

//签约单位
let complaintUnit = [];
//制单公司
$.ajax({
    url: "company/getAllMakerUnit",
    success: function (res) {
        if (res.status == 200) {
            complaintUnit = res.data;
            $.each(res.data, function (index, item) {
                if(item){
                    $("#complaintUnit").append(new Option(item.name, item.code));
                }
            });
            form.render('select');
        } else {
            layer.msg(res.msg, {icon: 5});
        }
    }
});
form.render('select');

layer.ready(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    let userTree = [];
    if(treeList && treeList.list){
        userTree = getAllJson(treeList.list);
    }else {
        userTree = getAllJson([{name: user.name, code: user.code}]);
    }

    operationNoList = getxmselect("#executor","executor", userTree);
    salesmanCodeList = getxmselect("#salesman","salesman", userTree);
    let operationCodes = operationNoList.getValue("value").join();
    let salesmanCodes = salesmanCodeList.getValue("value").join();
    if(user.code === "admin"){
        operationCodes = "admin";
        salesmanCodes = "admin";
    }

    inquiryPlatformList=getxmselect("#inquiryPlatformCode","inquiryPlatformCode", getAllJson(inquiryPlatform));

    let obj = {executor : operationCodes, salesman : salesmanCodes};
    initTable(obj);
});

function initTable(obj){
    table.render({
        elem: '#pollingdiscselect'
        ,url: 'inquiry/selectInquiryListByPage'
        ,where:obj
        ,id: 'pollingdisctableid'
        ,toolbar: '#pollingdisctoolbar'
        ,cellMinWidth: 120
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'oddNumber', title:'询价单号',sort:true,width: 170,event: "oddNumberEvent"}
            ,{field:'inquiryPlatformName', title:'询盘平台',sort:true}
            ,{field:'customerSimpleName', title:'客户简称'}
            ,{field:'salesmanName', title:'业务员'}
            ,{field:'customerCode', title:'编码'}
            ,{field:'customerName', title:'客户名称'}
            ,{field:'email', title:'邮箱地址'}
            ,{field:'customerContactName', title:'联系人'}
            ,{field:'currency', title:'币种',
                templet: function(data) {
                    let name = "";
                    $.each(currencyList, function(index, item) {
                        if (data.currency==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'complaintUnit', title:'制单公司',width: 120,style:"overflow:hidden",
                templet: function(data) {
                    let name = "";
                    $.each(complaintUnit, function(index, item) {
                        if(item){
                            if (data.complaintUnit==item.code){
                                name = item.name;
                                return ;
                            }
                        }
                    });
                    return name;
                }
            }
            ,{field:'inquiryTime', title:'询价日期',sort:true}
            ,{field:'feedbackTime', title:'反馈日期',sort:true}
            ,{field:'createTime', title:'创建日期',sort:true}
            ,{field:'executor', title:'操作员',
                templet: function(data) {
                    let name = "";
                    $.each(userList, function(index, item) {
                        if (data.executor==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'boxStatus', title:'单据类型',
                templet: function(data) {
                    switch (data.boxStatus) {
                        case "1": return "草稿箱";
                        case "2": return "待批箱";
                        case "3": return "已批箱";
                        case "4": return "完成箱";
                        case "5": return "垃圾箱";
                    }
                }
            }
            /*,{templet: '#checktherecord', title:'历史记录',width:100}*/
            ,{fixed: 'right', width:300, toolbar: '#pollingdisceditor', title:'操作'}
        ]]
        ,height: $(document).height() - $('#pollingdiscselect').offset().top - 50
        ,page: true
        ,limit: 50
        ,limits: [50, 100, 200, 300, 500]
    });
}

table.on('tool(pollingdisctable)', function(obj){
    var data = obj.data;
    if(obj.event === 'update') {
        parent.intab("views/jsp/other/tpl/newuppollingdisc.jsp?id="+obj.data.id,"修改询盘")
    }else if(obj.event === 'delect'){
        layer.confirm('确定删除吗', function (index) {
            if(deleteById(data.id)){
                obj.del();
                layer.close(index);
            }
        });
        return;
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', function (index) {
            update(data.id,data.boxStatus*1+1,"提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', function (index) {
            update(data.id,data.boxStatus*1+1,"审批通过");
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', function (index) {
            update(data.id,data.boxStatus-1,"审批退回");
        });
    }else if(obj.event === 'tomakeaninquiry'){
        layer.open({
            type: 2,
            area: $(window).width() < 458 ? "['100%', '100%']":['75%', '75%'],
            content: 'views/jsp/other/tpl/againmakeaninquiry.jsp?id='+obj.data.id
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', function (index) {
            update(data.id,data.boxStatus*1+1,"审批完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', function (index) {
            update(data.id,1,"审批还原");
        });
    }else if (obj.event === "oddNumberEvent"){
        parent.intab("views/jsp/other/tpl/viewpollingdisc.jsp?id="+obj.data.id,"询盘明细")
    }else if(obj.event === "checktherecord"){
        layer.open({
            type: 2,
            area: $(window).width() < 458 ? "['100%', '100%']":['75%', '75%'],
            content: 'views/jsp/other/tpl/checktherecord.jsp?id='+obj.data.id
        });
    }
});

form.on('submit(submitform)', function(data){
    initTable(data.field);
    return false;
});

table.on('toolbar(pollingdisctable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/other/tpl/newuppollingdisc.jsp","新增询盘")
            break;
        case 'dels':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList.length>0){
                layer.confirm('确定删除所选项吗？',function (index) {
                    var cbList = table.cache["pollingdisctableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("pollingdisctableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});

layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("statistical", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/other/tpl/inquiryStatistics1.jsp","询盘统计")
                break
        }
    });
})

function deleteById(delId) {
    let tf = false;
    $.ajax({
        type: 'POST',
        url: 'inquiry/delete/'+delId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if(res.data){
                    tf = true;
                    layer.msg("删除成功",{icon: 1});
                    table.reload('pollingdisctableid');
                }else{
                    layer.msg("删除失败",{icon: 4});
                }
            }else{
                layer.msg("删除失败",{icon: 2});
            }
        },
        error: function (data) {
            layer.msg("删除异常",{icon: 5});
        }
    });
    return tf;
}

//boxStatus 1 草稿 2 待批  3:已批 4 完成 5 垃圾
function update(id,boxStatus,titleName) {
    let tf = false;
    let msgInfo = "";
    let dataJson = {
        "id":id,
        "boxStatus":boxStatus
    };
    $.ajax({
        type: 'POST',
        data: JSON.stringify(dataJson),
        url: 'inquiry/updateBoxStatusBykey',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = true;
                msgInfo = titleName+"成功!"
                table.reload('pollingdisctableid');
            }else{
                msgInfo = titleName+"失败!"
            }
        },
        error: function (data) {
            msgInfo = titleName+"异常!"
        }
    });
    layer.msg(msgInfo);
    return tf;
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}